<?php
/**
 * Created by PhpStorm.
 * User: YongXuan.Huang
 * Date: 2017/10/2
 * Time: 23:35
 */

namespace Admin\Controller;

use Common\Common\FileSystem;
use Common\Common\Pagination;
use Common\Common\ResponseResult;
use Common\Common\Validator;
use Common\Model\Auth;
use Common\Model\Permissions;
use Common\Model\Role;
use Common\Model\RoleUsers;
use Common\Model\User;

class AdminUserController extends Controller
{
    /**
     * 用户列表
     */
    public function userList()
    {
        $this->checkPermission('edit-users');
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        if ($page < 1) {
            $page = 1;
        }
        $search = isset($_GET['search']) ? $_GET['search'] : null;
        $model = M('users');
        if ($search !== null) {
            $where = "username like '%{$search}%' or email like '%{$search}%'";
        } else {
            $where = 'id > 0';
        }
        $users = Pagination::make($page, 12, $model, $where);
        $data = array();
        foreach ($users->data as $item) {
            $item['role'] = User::init($item['id'])->role()->display_name;
            if ($item['is_baned'] == true) {
                if ($item['ban_time'] < 0) {
                    $item['ban'] = '永久';
                } else if ($item['ban_time'] > time()){
                    $item['ban'] = date('Y-m-d H:i:s', $item['ban_time']);
                }
            }
            $data[] = $item;
        }
        $this->assign('page', $page);
        $this->assign('search', $search);
        $this->assign('data', $data);
        $this->assign('users', $users);
        $this->display('admin/user/list');
    }

    /**
     * 删除用户
     */
    public function delete()
    {
        $this->checkPermission('edit-users');
        if (IS_POST) {
            $id = I('post.id', 0);
            if ($id < 1) {
                ResponseResult::error(1000, '参数不正确');
            }

            $model = M('users');
            $data = $model->where('id = ' . $id)->find();
            if (empty($data)) {
                ResponseResult::error(3000, '用户不存在');
            }
            $user = User::make($data);

            if ($user->role()->flag <= Auth::user()->role()->flag) {
                ResponseResult::error(2000, '此用户无法被你删除');
            }

            if ($model->delete($id)) {
                ResponseResult::success('删除成功');
            } else {
                ResponseResult::error(2000, '删除失败');
            }
        }
        ResponseResult::error(404, '失败的请求');
    }

    /**
     * 编辑用户
     */
    public function edit()
    {
        $this->checkPermission('edit-users');
        $id = intval(I('get.id', 0));
        if ($id < 1) {
            $this->error('数据不存在', '/admin/user/list');
        }
        $user = User::init($id);
        if ($user === null) {
            $this->error('数据不存在', '/admin/user/list');
        }
        if ($user->role()->flag <= Auth::user()->role()->flag) {
            $this->error('权限不足，无法编辑此用户', '/admin/user/list');
        }
        $roles = M('roles')->where('flag > ' . Auth::user()->role()->flag)->select();
        $this->assign('tagger', $user);
        $this->assign('roles', $roles);
        $this->display('admin/user/edit');
    }

    /**
     * 更新用户
     */
    public function update()
    {
        $this->checkPermission('edit-users');
        if (IS_POST) {
            $validator = Validator::make(array_merge($_POST, $_FILES), [
                'id' => ['required', 'integer', 'exists:users,id'],
                'username' => ['required', 'max:32', 'min:4', 'unique:users,username,' . $_POST['id']],
                'email' => ['required', 'email', 'unique:users,email,' . $_POST['id']],
                'password' => ['max:32', 'min:8'],
                'avatar' => ['file:image'],
                'age' => ['integer', 'between:1,200'],
                'sex' => ['integer', 'between:0,1'],
                'role' => ['required', 'exists:roles,id']
            ]);
            if ($validator->filed()) {
                $this->error('参数错误', '/admin/user/list', '', $validator);
            }
            $data = array_only($_POST, ['id', 'username', 'password', 'age', 'sex', 'email']);

            if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
                $data['avatar'] = FileSystem::uploadFile('avatar');
            }
            $id = intval($data['id']);
            $user = User::init($id);
            if ($user === null) {
                $this->error('请求错误', '/admin/user/list');
            }

            if ($user->role()->flag <= Auth::user()->role()->flag) {
                $this->error('权限不足，无法编辑此用户', '/admin/user/list');
            }
            if (in_array('password', array_keys($data))) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            if ($user->update($data)) {
                RoleUsers::update($user->id, $_POST['role']);
                $this->success('更新成功', '/admin/user/edit?id=' . $id);
            } else {
                $this->error('更新失败', '/admin/user/edit?id=' . $id);
            }
        } else {
            $this->error('请求错误', '/admin/user/list');
        }
    }

    /**
     * 添加用户
     */
    public function add()
    {
        $this->checkPermission('edit-users');
        $this->display('admin/user/add');
    }

    /**
     * 角色和许可列表
     */
    public function role()
    {
        $this->checkPermissions(['role-edit', 'role-permission']);
        $roles = M('roles')->select();
        $this->assign('roles', $roles);
        $permissions = M('permissions')->select();
        $this->assign('permissions', $permissions);
        $this->display('admin/user/role');
    }

    /**
     * 获取制定id的角色
     */
    public function getRole()
    {
        $this->checkPermissions(['role-edit']);
        $validator = Validator::make($_REQUEST, [
            'id' => ['required', 'exists:roles,id']
        ]);
        if ($validator->filed()) {
            ResponseResult::error(1000, '数据不存在');
        }
        ResponseResult::success(new Role($_REQUEST['id']));
    }

    /**
     * 添加创建角色
     */
    public function addRole()
    {
        $this->checkPermissions(['role-edit']);
        if (!IS_POST) {
            $this->error('请求错误', '/admin/user/role');
        }
        $validator = Validator::make($_POST, [
            'name' => ['required', 'unique:roles,name', 'max:32', 'min:4'],
            'display_name' => ['required', 'max:32', 'min:4'],
            'description' => ['required', 'max:64', 'min:4'],
            'flag' => ['required', 'between:2,99'],
            'permissions' => ['is_array']
        ]);
        if ($validator->filed()) {
            $this->error('添加失败', '', false, $validator);
        }

        if (Role::add(array_only($_POST, ['name', 'display_name', 'description', 'flag']), $_POST['permissions'])) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    /**
     * 删除角色
     */
    function deleteRole()
    {
        $this->checkPermissions(['role-edit']);
        if (!IS_POST) {
            ResponseResult::error(1000, '请求错误');
        }
        $validator = Validator::make($_POST, [
            'id' => ['required', 'exists:roles,id']
        ]);
        if ($validator->filed()) {
            ResponseResult::error(-1000, $validator->error());
        }
        $role = M('roles')->where('id = ' . $_POST['id'])->find();
        if ($role['id'] <= 2) {
            ResponseResult::error(2000, '此角色无法被删除');
        }

        if (M('roles')->where('id = ' . $_POST['id'])->delete() === false) {
            ResponseResult::error(3000, '删除失败');
        }
        ResponseResult::success('删除成功');
    }

    /**
     * 更新角色
     */
    public function updateRole()
    {
        $this->checkPermissions(['role-edit']);
        if (!IS_POST) {
            $this->error('请求错误');
        }
        $validator = Validator::make($_POST, [
            'id' => ['required', 'exists:roles,id'],
            'display_name' => ['required', 'max:32', 'min:4'],
            'description' => ['required', 'max:64', 'min:4'],
            'flag' => ['required', 'between:2,99'],
            'permissions' => ['is_array']
        ]);

        if ($validator->filed()) {
            $this->error('数据错误', '', false, $validator);
        }

        Role::update($_POST['id'], array_only($_POST, ['display_name', 'description', 'flag']), $_POST['permissions']);
        $this->success('更新成功');
    }

    /**
     * 创建许可
     */
    public function insertPermission()
    {
        $this->checkPermissions(['role-permission']);
        if (!IS_POST) {
            $this->error('请求错误');
        }
        $validator = Validator::make($_POST, [
            'name' => ['required', 'unique:permissions,name', 'max:32', 'min:4'],
            'display_name' => ['required', 'max:32', 'min:4'],
            'description' => ['required', 'max:64', 'min:4'],
        ]);
        if ($validator->filed()) {
            $this->error('数据错误', '', false, $validator);
        }
        if (Permissions::creates(array_only($_POST, ['name', 'display_name', 'description']))) {
            $this->success('创建成功');
        } else {
            $this->error('创建失败');
        }
    }

    /**
     * 更新许可
     */
    public function updatePermission()
    {
        $this->checkPermissions(['role-permission']);
        if (!IS_POST) {
            ResponseResult::error(1000, '请求错误');
        }
        $validator = Validator::make($_POST, [
            'id' => ['required', 'exists:permissions,id'],
            'display_name' => ['max:32', 'min:4'],
            'description' => ['max:64', 'min:4'],
        ]);

        if ($validator->filed()) {
            ResponseResult::error(-1000, $validator->error());
        }
        $data = array_only($_POST, ['display_name', 'description']);
        if (empty($data)) {
            ResponseResult::error(2000, '缺少相关的数据');
        }
        if (Permissions::update($_POST['id'], $data)) {
            ResponseResult::success('更新成功');
        } else {
            ResponseResult::error(3000, '更新失败');
        }
    }

    /**
     * user Ban
     */
    public function ban()
    {
        $this->checkPermissions(['edit-users']);
        if (!IS_POST) {
            ResponseResult::error(1000, '请求错误');
        }
        $validator = Validator::make($_POST, [
            'id' => ['required', 'exists:users,id'],
            'time' => 'required|integer'
        ]);
        if ($validator->filed()) {
            ResponseResult::error(2000, $validator->error());
        }
        $user = User::init($_POST['id']);
        if ($user === null) {
            $this->error('请求错误', '/admin/user/list');
        }

        if ($user->role()->flag <= Auth::user()->role()->flag) {
            $this->error('权限不足，无法编辑此用户', '/admin/user/list');
        }

        $time = intval($_POST['time']);
        $data = ['is_baned' => true, 'ban_time' => time() + $time * 60];
        if ($time === 0) {
            $data['is_baned'] = false;
            $data['ban_time'] = 0;
        }else if ($time < 0) {
            $data['ban_time'] = -1;
        }
        $user->update($data);
        ResponseResult::success('更新成功');
    }
}